from fastapi import APIRouter, Depends, HTTPException, status
from mysql.connection import get_connection
from routers.ie.ieModels import RuleModel, RuleUsername, IEModel
from auth.jwt import decode_token
from ie.ie import ie

router = APIRouter()

@router.post("/add_rule")
async def __add_rule(rule_model: RuleModel, token: dict = Depends(decode_token)):
    print(rule_model.title, rule_model.rules, rule_model.username)
    if rule_model.username == "":
        return {
            "code": 1,
            "detail": "未解析的用户名"
        }
    if rule_model.title == "":
        return {
            "code": 1,
            "detail": "未解析的标题"
        }
    if rule_model.rules.__len__() == 0:
        return {
            "code": 1,
            "detail": "未解析的规则"
        }
    connect = get_connection()
    with connect.cursor() as cursor:
        sql = "SELECT * FROM users WHERE username=%s AND dirty=0"
        cursor.execute(sql, rule_model.username)
        result = cursor.fetchall()
        if len(result) == 0:
            return {
                "code": 2,
                "detail": "未查询的用户名"
            }
        user_id = result[0]["id"]
        sql = "INSERT INTO rules(title, user_id, rule) VALUES(%s, %s, %s)"
        cursor.execute(sql, (rule_model.title, user_id.__str__(), rule_model.rules.__str__()))
    return {
        "code": 0
    }


@router.post("/get_rules")
async def __get_rules(rule_username: RuleUsername, token: dict = Depends(decode_token)):
    print(rule_username.username)
    if rule_username.username == "":
        return {
            "code": 1,
            "detail": "解析为空的用户名"
        }
    connect = get_connection()
    with connect.cursor() as cursor:
        sql = "SELECT * FROM users WHERE username=%s AND dirty=0"
        cursor.execute(sql, rule_username.username)
        result = cursor.fetchall()
        if len(result) == 0:
            return {
                "code": 2,
                "detail": "未查询的用户名"
            }
        user_id = result[0]["id"]
        sql = "SELECT * FROM rules WHERE user_id=%s AND dirty=0"
        cursor.execute(sql, user_id)
        result = cursor.fetchall()
        for i in range(len(result)):
            result[i]["rule"] = eval(result[i]["rule"])
    return {
        "code": 0,
        "rules": result
    }

@router.post("/ie")
async def __ie(ie_model: IEModel, token: dict = Depends(decode_token)):
    connect = get_connection()
    with connect.cursor() as cursor:
        sql = "SELECT * FROM users WHERE username=%s AND dirty=0"
        cursor.execute(sql, ie_model.username)
        result = cursor.fetchall()
        if len(result) == 0:
            return {
                "code": 2,
                "detail": "未查询的用户名"
            }
        user_id = result[0]["id"]
        result = []
        for item in ie_model.rules:
            rule = item["rule"]
            final_rule = []
            for iter in rule:
                final_rule.append(iter["info"])
            res = ie(ie_model.text, final_rule)
            result.append(res)
        sql = "INSERT INTO history(user_id, text, detail) VALUES (%s, %s, %s)"
        cursor.execute(sql, (user_id, ie_model.text, result.__str__()))
    return {
        "code": 0,
        "rules": result
    }

@router.post("/get_history")
async def __get_history(rule_username: RuleUsername, token: dict = Depends(decode_token)):
    connect = get_connection()
    with connect.cursor() as cursor:
        sql = "SELECT * FROM users WHERE username=%s AND dirty=0"
        cursor.execute(sql, rule_username.username)
        result = cursor.fetchall()
        if len(result) == 0:
            return {
                "code": 2,
                "detail": "未查询的用户名"
            }
        user_id = result[0]["id"]
        sql = "SELECT * FROM history WHERE user_id=%s AND dirty=0 ORDER BY id DESC"
        cursor.execute(sql, user_id)
        result = cursor.fetchall()
        for iter in result:
            iter["detail"] = eval(iter["detail"])
    return {
        "code": 0,
        "history": result
    }
